const bcrypt = require('bcryptjs')

const { getUserInfo } = require('../service/users.service')
const { userFormateError,
  userAlreadyExited,
  userRegisterError,
  userLoginError,
  usernameExited,
  passwordExited
} = require('../constant/err.type')
// 存放users模块会用到的中间件
// 空校验
const userValidator = async (ctx, next) => {
  const { username, password } = ctx.request.body
  if (!username?.trim() || !password?.trim()) {
    console.error('用户名或密码为空', ctx.request.body)
    ctx.app.emit('error', userFormateError, ctx)
    return
  }
  await next()
}

// 合理性校验
// 注册非重复合理性
const userVerify = async (ctx, next) => {
  const { username } = ctx.request.body
  // 传入用户名 , 如果已经存在会返回一个用户属性 , 需要传入一个对象
  try {
    const res = await getUserInfo({ username })
    if (res) {
      console.error('用户名已存在', { username })
      ctx.app.emit('error', userAlreadyExited, ctx)
      return
    }
  } catch (err) {
    console.log(err)
    ctx.app.emit('error', userRegisterError, ctx)
  }
  await next()
}
// 登录校验
const loginVerify = async (ctx, next) => {
  const { username, password } = ctx.request.body
  console.log(username, password, '这')
  try {
    const res = await getUserInfo({ username })
    console.log(res)
    if (!res) {
      console.error('用户名不存在', { username })
      ctx.app.emit('error', usernameExited, ctx)
      return
    }
    console.log(bcrypt.compareSync(password, res.password))
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit('error', passwordExited, ctx)
      return
    }
  } catch (err) {
    console.log(err)
    ctx.app.emit('error', userLoginError, ctx)
  }
  await next()
}
// 密码加密
const cryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body
  const salt = bcrypt.genSaltSync(10) // 加盐十次
  // hash保存密码的密文
  const hash = bcrypt.hashSync(password, salt)
  // 改写body
  ctx.request.body.password = hash
  await next()
}
module.exports = {
  userValidator,
  userVerify,
  loginVerify,
  cryptPassword
}